#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
数据库查看工具
"""
import sqlite3
import os

def view_database():
    """查看数据库内容"""
    db_path = 'dev.db'
    
    if not os.path.exists(db_path):
        print(f"❌ 数据库文件不存在: {db_path}")
        return
    
    print(f"📊 数据库文件: {db_path}")
    print("=" * 50)
    
    try:
        # 连接数据库
        conn = sqlite3.connect(db_path)
        cursor = conn.cursor()
        
        # 查看所有表
        cursor.execute("SELECT name FROM sqlite_master WHERE type='table';")
        tables = cursor.fetchall()
        
        print("📋 数据库中的表:")
        for i, table in enumerate(tables, 1):
            print(f"  {i}. {table[0]}")
        
        print("\n" + "=" * 50)
        
        # 查看用户表
        if ('auth_user',) in tables:
            print("👥 用户表 (auth_user):")
            cursor.execute("""
                SELECT id, username, email, is_superuser, is_staff, is_active, date_joined 
                FROM auth_user
            """)
            users = cursor.fetchall()
            
            if users:
                print("  ID | 用户名     | 邮箱              | 超级用户 | 员工 | 激活 | 注册时间")
                print("  " + "-" * 75)
                for user in users:
                    print(f"  {user[0]:2} | {user[1]:10} | {user[2]:17} | {user[3]:8} | {user[4]:4} | {user[5]:4} | {user[6]}")
            else:
                print("  没有用户数据")
        
        # 查看会话表
        if ('django_session',) in tables:
            print(f"\n🔐 会话表 (django_session):")
            cursor.execute("SELECT COUNT(*) FROM django_session")
            session_count = cursor.fetchone()[0]
            print(f"  活跃会话数: {session_count}")
        
        # 查看内容类型表
        if ('django_content_type',) in tables:
            print(f"\n📝 内容类型表 (django_content_type):")
            cursor.execute("SELECT COUNT(*) FROM django_content_type")
            content_type_count = cursor.fetchone()[0]
            print(f"  内容类型数: {content_type_count}")
        
        conn.close()
        
    except Exception as e:
        print(f"❌ 访问数据库时出错: {e}")

def show_table_structure(table_name):
    """显示表结构"""
    db_path = 'dev.db'
    
    try:
        conn = sqlite3.connect(db_path)
        cursor = conn.cursor()
        
        cursor.execute(f"PRAGMA table_info({table_name})")
        columns = cursor.fetchall()
        
        print(f"\n📊 表结构: {table_name}")
        print("  列名              | 类型      | 非空 | 默认值 | 主键")
        print("  " + "-" * 60)
        
        for col in columns:
            print(f"  {col[1]:16} | {col[2]:9} | {col[3]:4} | {col[4] or 'NULL':6} | {col[5]:4}")
        
        conn.close()
        
    except Exception as e:
        print(f"❌ 查看表结构时出错: {e}")

if __name__ == "__main__":
    print("🗄️ Django MES 数据库查看工具")
    print("=" * 50)
    
    view_database()
    
    # 显示重要表的结构
    show_table_structure('auth_user')
    
    print("\n" + "=" * 50)
    print("💡 提示:")
    print("  - 数据库文件位置: ./dev.db")
    print("  - 可以使用SQLite浏览器软件打开此文件")
    print("  - 推荐工具: DB Browser for SQLite")
    print("  - 下载地址: https://sqlitebrowser.org/") 